package org.gwu.seuss.client.commandline;

import java.io.File;

import org.gwu.seuss.communication.util.PasswordValidator;
import org.gwu.seuss.ui.commandline.BaseCommandLineArgs;
import org.gwu.seuss.ui.validator.RequestValidator;

public class ClientValidator extends RequestValidator {

	@Override
	public <T extends BaseCommandLineArgs> boolean isValid(T cli) {
		CommandLineArgs cla = (CommandLineArgs) cli;

		if (tooManyArguments(cla)) {
			errorMessage = "too many arguments provided";
			return false;
		}
		if (cla.getUpload() != null) {
			return isValidFile(cla.getUpload());
		}
		if(cla.getNewPassword() != null){
			return isValidPassword(cla.getNewPassword());
		}
		return true;
	}

	private boolean isValidPassword(String newPassword) {
		PasswordValidator pv = new PasswordValidator();
		boolean result = pv.validate(newPassword);
		errorMessage = result ? "" : "Invalid Password";
		return result;
	}

	
	// Check to see if file exists
	private boolean isValidFile(String upload) {
		if (!new File(upload).exists()) {
			errorMessage = "File does not exist on host system";
			return false;
		}
		return true;
	}

	private boolean tooManyArguments(CommandLineArgs cla) {

		if (cla.getDeleteFile() != null
				&& (cla.isFileList() || cla.getDownload() != null
						|| cla.getNewPassword() != null
						|| cla.getNewEmail() != null || cla.getUpload() != null)) {
			return true;
		} else if (cla.getDownload() != null
				&& (cla.isFileList()
				|| cla.getDeleteFile() != null || cla.getNewPassword() != null
						|| cla.getNewEmail() != null || cla.getUpload() != null)) {
			return true;
		} else if (cla.getNewPassword() != null
				&& (cla.isFileList() || cla.getDeleteFile() != null
						|| cla.getDownload() != null
						|| cla.getNewEmail() != null || cla.getUpload() != null)) {
			return true;
		} else if (cla.getNewEmail() != null
				&& (cla.isFileList() || cla.getDeleteFile() != null
						|| cla.getDownload() != null
						|| cla.getNewPassword() != null || cla.getUpload() != null)) {
			return true;
		} else if (cla.getUpload() != null
				&& (cla.isFileList() || cla.getDeleteFile() != null
						|| cla.getDownload() != null
						|| cla.getNewPassword() != null || cla.getNewEmail() != null)) {
			return true;
		} else if (cla.isFileList()
				&& (cla.getUpload() != null || cla.getDeleteFile() != null
						|| cla.getDownload() != null
						|| cla.getNewPassword() != null || cla.getNewEmail() != null)) {
			return true;
		} else {
			return false;
		}
	}
}
